package labs.third;

import static labs.utilities.PrintUtilities.printError;
import static labs.utilities.PrintUtilities.printException;
import static labs.utilities.PrintUtilities.printInfo;

import java.util.ArrayList;

import labs.utilities.LabsFileReader;
import labs.utilities.LabsFileWriter;

public class Parser {

	private final String inputFileName;
	private final String outputFileName;
	private labs.utilities.LabsFileReader reader;
	private labs.utilities.LabsFileWriter writer;
	private ArrayList<String> tokens;
	private boolean writeToFile;

	public Parser(String fileName, boolean writeToFile) {
		this.inputFileName = fileName;
		this.outputFileName = formatOutputFile();
		tokens = new ArrayList<String>();
		this.writeToFile = writeToFile;
	}

	public Parser(String fileName) {
		this(fileName, true);
	}

	public void start() {
		try {
			printInfo("Start Parsing File: '%s'", inputFileName);
			reader = new LabsFileReader(inputFileName);
			String[] lines = reader.readLines(true);
			printInfo("%s lines are read", lines.length);
			lines = null;
			if (reader.isOpened()) {
				reader.reset();
				printInfo("Start parsing process. . .");
				Lexer.parse(reader.getStreamReader(), tokens);
				reader.close();
				printInfo("%s tokens are extracted", tokens.size());
				if (writeToFile) {
					writeOutput();
					printInfo("Output is written to File: '%s'", outputFileName);
				}
			}
			printInfo("End Parsing File: '%s'", inputFileName);
		} catch (Exception e) {
			printError("Some error at lab-3");
			printException(e);
		}
	}

	private String formatOutputFile() {
		int extensionIndex = inputFileName.lastIndexOf('.');
		int fileNameIndex = inputFileName.lastIndexOf('\\') + 1;
		return String.format("%s%sOut-generated%s",
				inputFileName.substring(0, fileNameIndex),
				inputFileName.substring(fileNameIndex, extensionIndex), ".txt");
	}

	private void writeOutput() {
		writer = new LabsFileWriter(outputFileName);
		writer.writeLines(tokens.toArray(new String[tokens.size()]));
		writer.close();
	}

}
